import {
  Button,
  Row,
  Col,
  Image,
  Modal,
  Upload,
  message,
  Pagination,
} from 'antd'
import React, { ChangeEvent, Fragment, memo, useEffect, useState } from 'react'
import ThemeCard from '../../components/themeCard'
import { errorUrl } from './constans'
import { StarOutlined, DeleteOutlined, InboxOutlined } from '@ant-design/icons'
import './style.less'
import { IImageItem } from './types'
import {
  fetchDelImage,
  fetchImageCollect,
  fetchImages,
} from '../../api/material'

const Material: React.FC = () => {
  const [imageList, setImageList] = useState<IImageItem[]>([])
  const [visible, setVisible] = useState<boolean>(false)
  const [current, setCurrent] = useState<number>(1)
  const [pageSize, setPageSize] = useState<number>(10)
  const [total, setTotal] = useState<number>(0)
  const [collect, setCollect] = useState<boolean>(false)
  useEffect(() => {
    reqData()
  }, [collect, pageSize, current])

  const reqData = () => {
    fetchImages({
      collect,
      page: current,
      per_page: pageSize,
    }).then((res: any) => {
      if (res.message === 'OK' && res.data) {
        const { total_count, results = [] } = res.data
        setImageList(results)
        setTotal(total_count)
      }
    })
  }
  const handleBtnClick = (flag: boolean) => {
    if (collect !== flag) {
      setCollect(flag)
    }
  }
  const handleBtnCollect = (id: number) => {
    fetchImageCollect(id, { collect: !collect }).then((res: any) => {
      if (res.message === 'OK' && res.data) {
        const list = imageList.filter((v) => v.id !== id)
        setImageList(list)
        setTotal(total - 1)
      }
    })
  }

  const handleBtnDel = (id: number) => {
    Modal.confirm({
      title: '删除提示',
      content: '删除之后不可恢复, 是否继续?',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return fetchDelImage(id).then(() => {
          console.log('ok')

          const list = imageList.filter((v) => v.id !== id)
          setImageList(list)
          return Promise.resolve()
        })
      },
      onCancel: () => {},
    })
  }

  const handleModalHide = () => {
    setVisible(false)
  }
  const handleUploadImg = () => {
    setVisible(true)
  }
  const token = window.localStorage.getItem('token')
  const props = {
    name: 'image',
    multiple: true,
    headers: {
      Authorization: `Bearer ${token}`,
    },
    action: 'http://api-toutiao-web.itheima.net/mp/v1_0/user/images',
    onChange(info: any) {
      const { status } = info.file

      if (status === 'done') {
        message.success(`success`)
        setVisible(false)
      } else if (status === 'error') {
        message.error(`error`)
      }
    },
    onDrop(e: any) {
      console.log('Dropped files', e.dataTransfer.files)
    },
  }
  const handlePageHcnage = (current: number, pageSize: number) => {
    setPageSize(pageSize)
    setCurrent(current)
  }
  const showTotal = (total: number) => `共${total}条`
  return (
    <Fragment>
      <ThemeCard title="素材管理" className="material">
        <div className="btn-group  flex-4">
          <div className="left-group">
            <Button
              className={collect ? '' : 'ant-btn-primary'}
              onClick={() => handleBtnClick(false)}
            >
              全部
            </Button>
            <Button
              className={!collect ? '' : 'ant-btn-primary'}
              onClick={() => handleBtnClick(true)}
            >
              收藏
            </Button>
          </div>
          <Button className="upload-btn" onClick={handleUploadImg}>
            上传图片
          </Button>
        </div>

        <div className="pics">
          <Row gutter={[16, 16]}>
            {imageList.length
              ? imageList.map((v, i) => (
                  <Col
                    className="gutter-row"
                    xs={24}
                    sm={12}
                    md={8}
                    lg={6}
                    xl={4}
                    key={v.id}
                  >
                    <div className="pic-item">
                      <Image src={v.url} fallback={errorUrl} height={150} />
                      <div className="opear-btn-wrap">
                        <Button
                          type="primary"
                          shape="circle"
                          danger
                          style={{ background: 'rgb(230 162 60)' }}
                          icon={<StarOutlined />}
                          size="small"
                          onClick={() => handleBtnCollect(v.id)}
                        ></Button>
                        <Button
                          type="primary"
                          shape="circle"
                          danger
                          size="small"
                          onClick={() => handleBtnDel(v.id)}
                          icon={<DeleteOutlined />}
                        ></Button>
                      </div>
                    </div>
                  </Col>
                ))
              : null}
          </Row>
        </div>
        {Boolean(total) && (
          <Pagination
            total={total}
            current={current}
            pageSize={pageSize}
            showTotal={showTotal}
            showSizeChanger
            showQuickJumper
            onChange={handlePageHcnage}
          />
        )}
      </ThemeCard>

      <Modal title="上传图片" visible={visible} footer={null}>
        <Upload.Dragger {...props}>
          {' '}
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>{' '}
        </Upload.Dragger>
        <p style={{ textAlign: 'center' }}>
          只能上传jpg/png文件，且不超过500kb
        </p>
      </Modal>
    </Fragment>
  )
}

export default memo(Material)
